package com.app.bimo.module_bookrack.mvp.ui.adapter;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.app.bimo.commonbusiness.util.Constant;
import com.app.bimo.commonbusiness.util.DataUtil;
import com.app.bimo.commonbusiness.util.GlideImagSetUtil;
import com.app.bimo.commonbusiness.util.MultiClickUtil;
import com.app.bimo.commonbusiness.util.RouterHub;
import com.app.bimo.commonbusiness.util.SystemUtil;
import com.app.bimo.commonbusiness.util.UiUtil;
import com.app.bimo.commonbusiness.view.recyclerview.HeadFootRecyclerView;
import com.app.bimo.commonbusiness.view.recyclerview.RecycleAdapterImpl;
import com.app.bimo.commonbusiness.view.recyclerview.RecyclerViewHolder;
import com.app.bimo.library_db.BookData;
import com.app.bimo.library_db.helper.ChapterHelper;
import com.app.bimo.module_bookrack.R;
import com.bytedance.sdk.openadsdk.DownloadStatusController;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.TTNativeAd;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import java.util.List;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar;


public class BookrackAdapter extends RecycleAdapterImpl<BookData> {
    public final static int LIST_TYPE = 1;
    public final static int FOOT_TYPR = 2;
    public final static int AD_TYPR = 3;

    public HeadFootRecyclerView listView;
    private boolean isGrid;

    public BookrackAdapter(Context context, List<BookData> list, HeadFootRecyclerView listView) {
        super(list, context);
        this.listView = listView;
        isGrid = ((GridLayoutManager) listView.getLayoutManager()).getSpanCount() == 3;
    }

    //onCreateViewHolder
    @Override
    public int getViewId(int type) {
        if (isGrid) {
            if (type == LIST_TYPE) {
                return R.layout.bookrack_home_adapter_grid;
            } else if (type == AD_TYPR) {
                return R.layout.bookrack_home_adapter_grid_ad;
            } else if (type == FOOT_TYPR) {
                return R.layout.bookrack_home_gfoot_add;
            }
        } else {
            if (type == LIST_TYPE) {
                return R.layout.bookrack_home_adapter_lin;
            } else if (type == AD_TYPR) {
                return R.layout.bookrack_home_adapter_lin_ad;
            } else if (type == FOOT_TYPR) {
                return R.layout.bookrack_home_lfoot_add;
            }
        }
        return type;
    }

    @Override
    public int getCount() {
//        Log.e("aaa", "-------------------");
//        for (int i = 0; i < list.size(); i++) {
//            Log.e("aaa", "getCount: " + list.get(i).toString()+"-----"+i);
//        }
        if (list.size() > 0) {
            return super.getCount() + 1;
        } else {
            return super.getCount();
        }
    }

    //onBindViewHolder
    @Override
    public void initView(RecyclerViewHolder thold, int position) {
        final Hold hold = (Hold) thold;
        final BookData data;

        if (position == getCount() - 1) {
            ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) hold.addBtn.getLayoutParams();
            if (isGrid) {
                lp.width = ((SystemUtil.getWidth(context) - SystemUtil.dip2px(context, 8 * 2)) / 3);
                hold.addBtn.setLayoutParams(lp);
            } else {
                lp.width = SystemUtil.getImgW80(context);
                hold.addBtn.setLayoutParams(lp);
            }
            hold.itemView.setOnClickListener(v -> {
//                ARUtil.navigationFragment(RouterHub.HOME_MAIN, v);
            });
        } else {
            data = getItem(position);
            setData(hold, data, position);
        }

    }

    //onBindViewHolder
    private void setData(Hold hold, BookData data, int position) {
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) hold.book.getLayoutParams();
        if (isGrid) {
            lp.width = (SystemUtil.getWidth(context) - SystemUtil.dip2px(context, 8 * 2)) / 3;
            hold.book.setLayoutParams(lp);
            GlideImagSetUtil.loadImgRoundedCornersCenterCrop(data.getCover(), hold.book, SystemUtil.dip2px(context, 3));
        } else {
            lp.width = SystemUtil.getImgW70(context);
            if (position == 0) {
                lp.setMargins(SystemUtil.dip2px(context, 6), SystemUtil.dip2px(context, 12), 0, 0);
            } else {
                lp.setMargins(SystemUtil.dip2px(context, 6), SystemUtil.dip2px(context, 3), 0, 0);
            }
            hold.book.setLayoutParams(lp);
            GlideImagSetUtil.loadImgRoundedCornersCenterCrop(data.getCover(), hold.book, SystemUtil.dip2px(context, 3));

        }
        if (data.getAd() != null) {
            initAdData(hold, data, position);

        } else {
            initNomalData(hold, data, position);
        }
    }

    @Override
    public RecyclerViewHolder getHold(int id) {
        return new Hold(id, context);
    }

    private void initNomalData(Hold hold, BookData data, int position) {
        if (data.getAd() != null) {
            return;
        }
        if (isGrid) {
            if (Integer.valueOf(data.getLastReadTime()) == 0) {
                hold.stadus.setText("未读过");
                UiUtil.setImgToTextView(context, R.drawable.dot_rff5400_6dp, hold.stadus, 4);
            } else if (Integer.valueOf(data.getLastReadTime()) > 0 && data.getUpdateChapterNum() > 0) {
                hold.stadus.setText("更新了" + data.getUpdateChapterNum() + "章");
                UiUtil.setImgToTextView(context, R.drawable.dot_rff5400_6dp, hold.stadus, 4);
            } else if (Integer.valueOf(data.getLastReadTime()) > 0 && data.getUpdateChapterNum() == 0) {
                hold.stadus.setText("阅读到：" + data.getLastChapterTitle());
                UiUtil.setImgToTextView(context, 0, hold.stadus, 4);
            }
        } else {
            hold.auther.setText(data.getAuthorName());
            if (Integer.valueOf(data.getLastReadTime()) == 0) {
                String s = "未读过  ";
                UiUtil.setImgSpannToTextView(hold.hint, s, R.drawable.dot_rff5400_6dp, s.length() - 1, s.length(), 6, SystemUtil.dip2px(context, 12));
                if (data.getUpdateChapterNum() > 0) {
                    hold.stadus.setText("更新了" + data.getUpdateChapterNum() + "章");
                } else {
                    hold.stadus.setText("暂无更新");
                }
            } else {
                String s = "阅读进度：" + data.getLastChapterTitle() + "";
                hold.hint.setText(s);
                if (data.getUpdateChapterNum() > 0) {
                    String stadusStr = "更新了" + data.getUpdateChapterNum() + "章  ";
                    UiUtil.setImgSpannToTextView(hold.stadus, stadusStr, R.drawable.dot_rff5400_6dp, stadusStr.length() - 1, stadusStr.length(), 6, SystemUtil.dip2px(context, 12));
                } else {
                    hold.stadus.setText("暂无更新");
                }
            }


            float progressStr = 0;
            if (!DataUtil.isEmpty(data.getReadSchedule())) {
                progressStr = Math.round(Float.valueOf(data.getReadSchedule()) * 1000) / 10;
//                progressStr = Math.round(progressStr * 10) / 10;
            }
            hold.progress.setProgress((int) progressStr);
            hold.progressTv.setText(progressStr + "%");
        }
        hold.bookName.setText(data.getNovelName());

        if (data.getIsRecommend() == 1) {
            hold.bookTop.setVisibility(View.VISIBLE);
            hold.bookTop.setText("推荐");
            hold.bookTop.setBackground(context.getResources().getDrawable(R.drawable.bg_blue_38a6fe_lr_rr_3dp));
        } else if (data.getPromotionType() == 1) {
            hold.bookTop.setVisibility(View.VISIBLE);
            hold.bookTop.setText("限免");
            hold.bookTop.setBackground(context.getResources().getDrawable(R.drawable.bg_rfa6061_lr_rr_3dp));
        } else {
            hold.bookTop.setVisibility(View.GONE);
        }


        hold.itemView.setOnClickListener(v -> {
            if (!MultiClickUtil.isFastClick()) return;
//            if (animListener != null){
////                animListener.onAnim(hold.book,data,hold.book);
////            }

            Bundle bundle = new Bundle();
            bundle.putString(Constant.BundleNovelid, data.getNovelid());
            if (!ChapterHelper.getInstance().isHaveCache(data.getNovelid())) {
                bundle.putString(Constant.BundleChapterId, data.getLastChapterid());
            }
//            ARUtil.navigationFragment(RouterHub.READ_BOOK, listView, bundle);

        });
        hold.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
//                ARUtil.navigationFragment(RouterHub.BOOKRACK_DEL, v);
                return true;
            }
        });

    }

    private void initAdData(Hold hold, BookData data, int position) {
        TTNativeExpressAd ad = data.getAd();
        if (ad == null) {
            return;
        }
//        //可以被点击的view, 也可以把convertView放进来意味item可被点击
//        List<View> clickViewList = new ArrayList<>();
//        clickViewList.add(hold.itemView);
//        //触发创意广告的view（点击下载或拨打电话）
//        List<View> creativeViewList = new ArrayList<>();
//        creativeViewList.add(hold.itemView);
//        //如果需要点击图文区域也能进行下载或者拨打电话动作，请将图文区域的view传入
////            creativeViewList.add(convertView);
//        //重要! 这个涉及到广告计费，必须正确调用。convertView必须使用ViewGroup。
        ad.render();
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
                Log.i("loadFeedAd", "广告被点击");
            }

            @Override
            public void onAdShow(View view, int type) {
                Log.i("loadFeedAd", "广告展示");
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                Log.e("loadFeedAd","render fail:"+(System.currentTimeMillis()));
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                Log.i("loadFeedAd", "onRenderSuccess");
//                //返回view的宽高 单位 dp
//                //在渲染成功回调时展示广告，提升体验

                hold.cl_ad_contain.removeAllViews();
                hold.cl_ad_contain.addView(view);

                ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                view.setLayoutParams(layoutParams);

//                Log.i("loadFeedAd","广告个数"+((ViewGroup)nativeView).getChildCount()+"             "+ ((ViewGroup)adPageView).getChildCount());
            }
        });

        //dislike设置
//        bindDislike(nativeView,nativeAd);




//             ad.registerViewForInteraction((ViewGroup) hold.itemView, clickViewList, creativeViewList, new TTNativeAd.AdInteractionListener() {
//            @Override
//            public void onAdClicked(View view, TTNativeAd ad) {
//                if (ad != null) {
////                    TToast.show(mContext, "广告" + ad.getTitle() + "被点击");
//                }
//            }
//
//            @Override
//            public void onAdCreativeClick(View view, TTNativeAd ad) {
//                if (ad != null) {
////                    TToast.show(mContext, "广告" + ad.getTitle() + "被创意按钮被点击");
//                }
//            }
//
//            @Override
//            public void onAdShow(TTNativeAd ad) {
//                if (ad != null) {
////                    TToast.show(mContext, "广告" + ad.getTitle() + "展示");
//                }
//            }
//        });
//        hold.bookName.setText(ad.getTitle());
//        if (isGrid) {
//            hold.tv_listitem_ad_source.setText(DataUtil.isEmpty(ad.getButtonText()) ? "立即体验" : ad.getButtonText());
//            hold.tv_listitem_ad_source1.setText("");
//        } else {
//            hold.tv_listitem_ad_source1.setText(DataUtil.isEmpty(ad.getButtonText()) ? "立即体验" : ad.getButtonText());
//            hold.tv_listitem_ad_source.setText(DataUtil.isEmpty(ad.getDescription()) ? "" : ad.getDescription());
//
//        }
//        bindDislikeAction(hold, data, ad, hold.iv_listitem_dislike);
//        TTImage icon = ad.getImageList().get(0);
//        if (icon != null && icon.isValid()) {
//            GlideImagSetUtil.loadImgRoundedCornersCenterCrop(icon.getImageUrl(), hold.book, SystemUtil.dip2px(context, 3));
//        }
//        View adCreativeButton = hold.itemView;
//        switch (ad.getInteractionType()) {
//            case TTAdConstant.INTERACTION_TYPE_DOWNLOAD:
//                //如果初始化ttAdManager.createAdNative(getApplicationContext())没有传入activity 则需要在此传activity，否则影响使用Dislike逻辑
//                if (context instanceof Activity) {
//                    ad.setActivityForDownloadApp((Activity) context);
//                }
//                adCreativeButton.setVisibility(View.VISIBLE);
////                hold.mStopButton.setVisibility(View.VISIBLE);
////                hold.mRemoveButton.setVisibility(View.VISIBLE);
////                bindDownloadListener(adCreativeButton, adViewHolder, ad);
////                绑定下载状态控制器
////                bindDownLoadStatusController(adViewHolder, ad);
//                break;
//            case TTAdConstant.INTERACTION_TYPE_DIAL:
//                adCreativeButton.setVisibility(View.VISIBLE);
////                adCreativeButton.setText("立即拨打");
////                hold.mStopButton.setVisibility(View.GONE);
////                hold.mRemoveButton.setVisibility(View.GONE);
//                break;
//            case TTAdConstant.INTERACTION_TYPE_LANDING_PAGE:
//            case TTAdConstant.INTERACTION_TYPE_BROWSER:
////                    adCreativeButton.setVisibility(View.GONE);
//                adCreativeButton.setVisibility(View.VISIBLE);
////                adCreativeButton.setText("查看详情");
////                hold.mStopButton.setVisibility(View.GONE);
////                hold.mRemoveButton.setVisibility(View.GONE);
//                break;
//            default:
//                adCreativeButton.setVisibility(View.VISIBLE);
////                hold.mStopButton.setVisibility(View.GONE);
////                hold.mRemoveButton.setVisibility(View.GONE);
////                TToast.show(mContext, "交互类型异常");
//        }
    }

    @Override
    public int getItemViewType(int position) {
        int type = super.getItemViewType(position);
        if (type == 0) {
            if (customHeaderView != null) {
                position--;
            }
            int size = getCount() - 1;
            if (size > 0 && position == size) {
                return FOOT_TYPR;
            } else {
                if (list.get(position).getAd() != null) {
                    return AD_TYPR;
                }
                return LIST_TYPE;
            }
        } else {
            return type;
        }
//        }
    }//接入网盟的dislike 逻辑，有助于提示广告精准投放度

    private void bindDislikeAction(Hold hold, BookData bookData, TTNativeAd ad, View dislikeView) {
        final TTAdDislike ttAdDislike = ad.getDislikeDialog((Activity) context);
        if (ttAdDislike != null) {
            ttAdDislike.setDislikeInteractionCallback(new TTAdDislike.DislikeInteractionCallback() {
                @Override
                public void onSelected(int position, String value) {
                    int index = list.indexOf(bookData);
                    list.remove(index);
                    notifyItemRemoved(index + 1);
                }

                @Override
                public void onCancel() {

                }
            });
        }
        dislikeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ttAdDislike != null)
                    ttAdDislike.showDislikeDialog();
            }
        });
    }

    private void bindDownLoadStatusController(Hold adViewHolder, final TTFeedAd ad) {
        final DownloadStatusController controller = ad.getDownloadStatusController();
//        adViewHolder.mStopButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (controller != null) {
//                    controller.changeDownloadStatus();
//                    TToast.show(mContext, "改变下载状态");
//                    Log.d(TAG, "改变下载状态");
//                }
//            }
//        });

//        adViewHolder.mRemoveButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (controller != null) {
//                    controller.cancelDownload();
//                    TToast.show(mContext, "取消下载");
//                    Log.d(TAG, "取消下载");
//                }
//            }
//        });
    }

//    private void bindDownloadListener(final Button adCreativeButton, final Hold adViewHolder, TTFeedAd ad) {
//        TTAppDownloadListener downloadListener = new TTAppDownloadListener() {
//            @Override
//            public void onIdle() {
//                if (!isValid()) {
//                    return;
//                }
////                adCreativeButton.setText("开始下载");
////                adViewHolder.mStopButton.setText("开始下载");
//            }
//
//            @SuppressLint("SetTextI18n")
//            @Override
//            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                if (totalBytes <= 0L) {
//                    adCreativeButton.setText("0%");
//                } else {
//                    adCreativeButton.setText((currBytes * 100 / totalBytes) + "%");
//                }
////                adViewHolder.mStopButton.setText("下载中");
//            }
//
//            @SuppressLint("SetTextI18n")
//            @Override
//            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                if (totalBytes <= 0L) {
//                    adCreativeButton.setText("0%");
//                } else {
//                    adCreativeButton.setText((currBytes * 100 / totalBytes) + "%");
//                }
//                adViewHolder.mStopButton.setText("下载暂停");
//            }
//
//            @Override
//            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                adCreativeButton.setText("重新下载");
//                adViewHolder.mStopButton.setText("重新下载");
//            }
//
//            @Override
//            public void onInstalled(String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                adCreativeButton.setText("点击打开");
//                adViewHolder.mStopButton.setText("点击打开");
//            }
//
//            @Override
//            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                if (!isValid()) {
//                    return;
//                }
//                adCreativeButton.setText("点击安装");
//                adViewHolder.mStopButton.setText("点击安装");
//            }
//
//            @SuppressWarnings("BooleanMethodIsAlwaysInverted")
//            private boolean isValid() {
//                return mTTAppDownloadListenerMap.get(adViewHolder) == this;
//            }
//        };
//        //一个ViewHolder对应一个downloadListener, isValid判断当前ViewHolder绑定的listener是不是自己
//        ad.setDownloadListener(downloadListener); // 注册下载监听器
//        mTTAppDownloadListenerMap.put(adViewHolder, downloadListener);
//    }

    class Hold extends RecyclerViewHolder {

        public Hold(int arg0, Context context) {
            super(arg0, context);
        }

        ImageView book;
        TextView bookName;
        TextView bookTop;
        //阅读进度
        TextView hint;
        //更新状态
        TextView stadus;
        TextView auther;
        TextView adName;
        TextView upNum;
        ImageView addBtn;


        //        ad

        TextView tv_listitem_ad_source;
        TextView tv_listitem_ad_source1;
        TextView iv_listitem_dislike;
        MaterialProgressBar progress;
        TextView progressTv;
        ConstraintLayout cl_ad_contain;


    }

    public interface AnimListener {
        void onAnim(View view, BookData bookData, ImageView imageView);
    }


}
